package cn.yunchongbao.charging.order.config;

import cn.yunchongbao.charging.order.mqtt.MqttConsumer;
import cn.yunchongbao.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MqttConfiguration {
    private String userName = "admin";
    private String password = "password";
    private String host = "tcp://localhost:1883";
    private String clientId = "order_service_client";

    @Autowired
    private MqttContext mqttContext;

    @Bean
    public MqttClient mqttClient() throws MqttException {
        MqttClient mqttClient = new MqttClient(host, clientId);
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setUserName(userName);
        mqttConnectOptions.setPassword(password.toCharArray());
        mqttConnectOptions.setCleanSession(true);
        mqttConnectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttClient.setCallback(new MqttConsumer(mqttContext,mqttClient));
        mqttClient.connect(mqttConnectOptions);
        return mqttClient;
    }
}